package com.example.testdemo.eventbus.queue

/**
 * Create Time:2020/8/13
 * Author: Lindanrong
 * Description:
 */
class BeanPostQueue {

    var head: BeanPost? = null
    var tail: BeanPost? = null

    private val lock = Object()

    fun enqueue(beanPost: BeanPost?) = synchronized(lock) {
        if (beanPost == null) {
            throw NullPointerException("null cannot be enqueued")
        }
        when {
            tail != null -> {
                tail?.next = beanPost
                tail = beanPost
            }
            head == null -> {
                tail = beanPost
                head = tail
            }
            else -> {
                throw IllegalStateException("Head present, but no tail")
            }
        }
        lock.notifyAll()
    }

    fun poll(): BeanPost? = synchronized(lock) {
        var beanPost: BeanPost? = null
        if (head != null) {
            beanPost = head
            head = head!!.next
            if (head == null) {
                tail = null
            }
        }
        return beanPost
    }


    @Throws(InterruptedException::class)
    fun poll(maxMillisToWait: Int): BeanPost? = synchronized(lock) {
        if (head == null) {
            lock.wait(maxMillisToWait.toLong())
        }
        return poll()
    }

}